package io.github.lee.app.unsplash.ui.detail.photo

import android.animation.ArgbEvaluator
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.widget.Toolbar
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.gyf.immersionbar.ktx.fitsTitleBar
import com.gyf.immersionbar.ktx.immersionBar
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.app.unsplash.R
import io.github.lee.app.unsplash.databinding.LayoutPhotoDetailFloatingBinding
import io.github.lee.app.unsplash.databinding.ToolbarDefaultCenterBinding
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.views.LoadStateAdapter
import io.github.lee.core.ui.BaseRefreshFragment
import io.github.lee.core.util.getArgumentParcelable
import io.github.lee.core.util.screenHeight
import io.github.lee.core.util.toPx
import io.github.lee.core.views.listener.setOnScrollDistanceListener


@AndroidEntryPoint
class PhotoDetailFragment : BaseRefreshFragment<PhotoDetailVM>() {

    private var toolbarVb: ToolbarDefaultCenterBinding? = null
    private val floatingVb by lazy {
        val v = LayoutPhotoDetailFloatingBinding.inflate(layoutInflater)
        val p = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        p.gravity = Gravity.END or Gravity.BOTTOM
        p.marginEnd = 16.toPx(mContext)
        p.bottomMargin = 36.toPx(mContext)
        v.root.layoutParams = p
        v
    }


    companion object {
        private const val KEY_PHOTO = "PHOTO"
        fun newInstance(photo: Photo): PhotoDetailFragment {
            val args = bundleOf(
                KEY_PHOTO to photo
            )
            val fragment = PhotoDetailFragment()
            fragment.arguments = args
            return fragment
        }
    }


    //===Desc:===============================================================================

    override fun onCreateToolbar(): Toolbar {
        toolbarVb = ToolbarDefaultCenterBinding.inflate(layoutInflater).also {
            it.bgColor = Color.TRANSPARENT
            it.titleColor = Color.WHITE
            val photo = getArgumentParcelable(KEY_PHOTO, Photo::class.java)
            it.title = photo?.user?.name ?: ""
        }
        return toolbarVb!!.toolbar
    }


    override fun onCreateViewModel(): PhotoDetailVM =
        viewModels<PhotoDetailVM>().value.also {
            val photo = getArgumentParcelable(KEY_PHOTO, Photo::class.java)
            if (null == photo) {
                showError()
                return@also
            }
            it.user = photo.user
        }


    override fun onCreateLayoutManager(): RecyclerView.LayoutManager =
        StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

    override fun onCreateTrailingLoadAdapter(): TrailingLoadStateAdapter<*> =
        LoadStateAdapter()


    //===Desc:===============================================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        enableRefresh = false
        enableLoadMore = false
        isHover = true
    }

    override fun onSetViewListener() {
        super.onSetViewListener()
        recyclerView?.setOnScrollDistanceListener { _, y ->
            val maxDistance = screenHeight(mContext) * 1.0F * 2 / 3
            val fraction = if (y >= maxDistance) {
                1F
            } else if (y <= 0) {
                0F
            } else {
                y / maxDistance
            }
            toolbarVb?.titleColor =
                ArgbEvaluator().evaluate(fraction, Color.WHITE, Color.TRANSPARENT) as Int

            //悬浮按钮的显示/隐藏
            if (1 - fraction <= 0) {
                floatingVb.root.visibility = View.GONE
            } else {
                floatingVb.fabLike.alpha = 1 - fraction
                floatingVb.fabDownload.alpha = 1 - fraction
                floatingVb.root.visibility = View.VISIBLE
            }
        }


        vm?.adapter?.setOnItemClickListener { adapter, _, position ->
            PhotoDetailActivity.start(mContext, adapter.items[position])
        }

    }

    override fun onSetViewData() {
        super.onSetViewData()
        immersionBar {
            transparentBar()
            fitsTitleBar(toolbarFrameLayout)
        }

        toolbar?.setNavigationIcon(R.drawable.baseline_arrow_back_ios_new_24)
        toolbar?.navigationIcon?.setTint(Color.WHITE)
        toolbar?.setNavigationOnClickListener {
            activity?.onBackPressed()
        }

        toolbar?.inflateMenu(R.menu.menu_photo_detail)
        toolbar?.setOnMenuItemClickListener {
            if (it.itemId == R.id.share) {
                Log.e("TAG", "Share")
                true
            } else {
                false
            }
        }

        recyclerView?.apply {
            itemAnimator = null
            setBackgroundColor(mContext.getColor(R.color.mainBackground))
        }

        val photo = getArgumentParcelable(KEY_PHOTO, Photo::class.java)
        if (null == photo) {
            showError()
            return
        }
        addHeaderAdapter(PhotoDetailHeaderAdapter(photo))
        addHeaderAdapter(RelatedHeaderAdapter())

        setupFloating(photo)



        vm?.onRefreshOrLoadMore(true)
    }

    private fun setupFloating(photo: Photo) {
        floatingVb.fabLike.setOnClickListener {
            Log.e("TAG", "Photo ${photo.id} like click")
        }
        floatingVb.fabDownload.setOnClickListener {
            Log.e("TAG", "Photo ${photo.id} download click")
        }

        addPageHoverView(floatingVb.root)
    }
}